package com.jadows.tdog.message.handler.impl;

import cn.hutool.core.collection.CollUtil;
import com.jadows.tdog.message.WsReqWrapper;
import com.jadows.tdog.message.details.WebRTCSDPMessage;
import com.jadows.tdog.message.handler.IMqMessageHandler;
import com.jadows.tdog.server.codec.JsonWebSocketFrame;
import com.jadows.tdog.state.OnlineUserRegister;
import com.jadows.tdog.state.SimpleWSSessionUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.Set;

import static com.jadows.tdog.constants.CacheConstants.WEBRTC_SDP_TOPIC;

@Component
@Slf4j
public class WebRTCSDPMessageHandler implements IMqMessageHandler<WsReqWrapper<WebRTCSDPMessage>> {

    final RTopic rTopic;
    final RedissonClient redissonClient;
    final OnlineUserRegister onlineUserRegister;


    public WebRTCSDPMessageHandler(RedissonClient redissonClient,
                                   OnlineUserRegister onlineUserRegister) {
        rTopic = redissonClient.getTopic(WEBRTC_SDP_TOPIC + onlineUserRegister.getCurrentInstanceId());
        rTopic.addListener(WsReqWrapper.class, (channel, msg) -> {
                    log.info("WebRTCSDPMessageHandler: {}", msg);
                    @SuppressWarnings("unchecked")
                    WsReqWrapper<WebRTCSDPMessage> reqWrapper = (WsReqWrapper<WebRTCSDPMessage>) msg;
                    this.arrived(reqWrapper);
                }
        );
        this.onlineUserRegister = onlineUserRegister;
        this.redissonClient = redissonClient;
    }

    @Override
    public Long publish(WsReqWrapper<WebRTCSDPMessage> message) {
        WebRTCSDPMessage callMessage = message.getData();
        String toUid = callMessage.getToUid();
        Set<String> userInstanceIds = onlineUserRegister.getUserInstanceId(toUid);
        long result = 0L;
        for (String instanceId : userInstanceIds) {
            String topicName = WEBRTC_SDP_TOPIC + instanceId;
            RTopic rTopic = redissonClient.getTopic(topicName);
            result += rTopic.publish(message);
        }
        return result;
    }

    @Override
    public void arrived(WsReqWrapper<WebRTCSDPMessage> message) {
        // 呼叫消息
        WebRTCSDPMessage webRtcCallMessage = message.getData();
        // 用户呼叫
        String toUid = webRtcCallMessage.getToUid();
        Set<Channel> channels = SimpleWSSessionUtil.getChannelByUid(toUid);
        if (CollUtil.isEmpty(channels)) {
            log.warn("用户不在线: {}", toUid);
            return;
        }
        channels.forEach(channel -> channel.writeAndFlush(new JsonWebSocketFrame(message)));
    }

}
